import {
  login,
  logout
} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import router, {resetRouter} from '@/router'
import ElementUI from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken(),
    avatar:localStorage.getItem('avatar') ? JSON.parse(localStorage.getItem('avatar')) : '',
    userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {},
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },

  SET_USERINFO: (state, info) => {
    state.userInfo = info
  }
}

const actions = {
  // user login
  login({commit}, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const {data,code} = response
        if (code === 200) {
          const {user, token} = data
          localStorage.setItem('userInfo', JSON.stringify(user))
          // localStorage.setItem('avatar', JSON.stringify(process.env.VUE_APP_BASE_API + user.avatar))
          localStorage.setItem('avatar', JSON.stringify('http://47.108.137.234:30001' + user.avatar))
          setToken(token)
          commit('SET_TOKEN', token)
          commit('SET_USERINFO', user)
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  setRefreshedToken({ commit }, newToken) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', newToken)
      setToken(newToken)
      resolve(newToken)
    })
  },


  // user logout
  logout({commit, state}) {
    return new Promise((resolve) => {
      logout().then(response =>{
        const { code } = response;
        if(code == 200){
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          localStorage.clear()
          resolve()
        }
      })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      // refreshToken().then(res =>{
      //   removeToken() // must remove  token  first
      //   commit('RESET_STATE')
      //   resolve()
      // })
    })
  },


  // 修改用户密码
  editUserPassword({}, data) {
    return new Promise((resolve, reject) => {
      editPassword(data).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 修改用户签名
  editUserSignature({}, data) {
    return new Promise((resolve, reject) => {
      editSignature(data).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
